<script setup>
import { ref, onMounted, computed } from 'vue';
import { getAllClinicsService, addClinicService, deleteClinicService, getAllDepartmentsService,updateClinicService } from '@/api/hospital.js'; // 导入相关的API函数
import { ElMessage, ElMessageBox } from 'element-plus';

// 定义科室列表数据
const clinics = ref([]);
const dialogVisible = ref(false);
const newClinic = ref({
    clinicId: null,
    clinicName: '',
    clinicDescription: '',
    departmentId: null,
    departmentName: ''
});

// 定义部门列表数据
const departments = ref([]);

// 获取所有科室信息的函数
const fetchClinics = async () => {
    try {
        const response = await getAllClinicsService(); // 获取所有科室信息
        if (response.code === 0) {
            clinics.value = response.data; // 更新科室数据
        } else {
            ElMessage.error(response.message || '获取科室信息失败');
        }
    } catch (error) {
        ElMessage.error('获取科室信息失败');
    }
};

// 获取所有部门信息的函数
const fetchDepartments = async () => {
    try {
        const response = await getAllDepartmentsService(); // 获取所有部门信息
        if (response.code === 0) {
            departments.value = response.data.map(department => ({
                id: department.departmentId, // 使用 departmentId
                name: department.departmentName || '未命名部门' // 使用 departmentName，提供默认值
            })); // 更新部门数据
        } else {
            ElMessage.error(response.message || '获取部门信息失败');
        }
    } catch (error) {
        ElMessage.error('获取部门信息失败');
    }
};

// 打开添加科室信息的对话框
const openAddDialog = async () => {
    // 获取当前已存在的科室ID列表
    const existingIds = clinics.value.map(clinic => clinic.clinicId);
    // 自动生成一个未被使用的科室ID
    newClinic.value.clinicId = generateUnusedClinicId(existingIds); // 生成科室ID
    newClinic.value.clinicName = ''; // 重置科室名称
    newClinic.value.clinicDescription = ''; // 重置科室描述
    newClinic.value.departmentId = null; // 重置部门ID
    dialogVisible.value = true; // 显示对话框
};

// 添加科室信息的函数
const addClinic = async () => {
    try {
        // 获取当前已存在的科室ID列表
        const existingIds = clinics.value.map(clinic => clinic.clinicId);
        // 自动生成一个未被使用的科室ID
        newClinic.value.clinicId = generateUnusedClinicId(existingIds);
        
        const response = await addClinicService(newClinic.value); // 直接传递科室对象
        if (response.code === 0) {
            ElMessage.success('添加成功');
            dialogVisible.value = false; // 关闭对话框
            fetchClinics(); // 重新获取科室列表
        } else {
            ElMessage.error(response.message || '添加失败');
        }
    } catch (error) {
        ElMessage.error('添加失败');
    }
};

// 生成未被使用的科室ID的函数
const generateUnusedClinicId = (existingIds) => {
    let newId = 1; // 从1开始
    while (existingIds.includes(newId)) {
        newId++;
    }
    return newId;
};

// 删除科室信息的函数
const deleteClinic = async (clinicId) => {
    try {
        await ElMessageBox.confirm('确定要删除该科室吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        const response = await deleteClinicService(clinicId);
        if (response.code === 0) {
            ElMessage.success('删除成功');
            fetchClinics(); // 重新获取科室列表
        } else {
            ElMessage.error(response.message || '删除失败');
        }
    } catch (error) {
        ElMessage.error('删除失败');
    }
};

// 在组件挂载时获取科室数据
onMounted(() => {
    fetchClinics(); // 直接获取所有科室数据
    fetchDepartments(); // 获取所有部门数据
});

const currentPage = ref(1);
const pageSize = 8;

// 计算分页后的科室数据
const paginatedClinics = computed(() => {
    const start = (currentPage.value - 1) * pageSize;
    return clinics.value.slice(start, start + pageSize);
});

// 处理页码变化
const handleCurrentChange = (page) => {
    currentPage.value = page;
};

const updateDialogVisible = ref(false);
const updateClinic = ref({}); // 用于存储更新的科室信息

// 打开更新科室信息的对话框
const openUpdateDialog = (clinic) => {
    updateClinic.value = { ...clinic }; // 复制原始信息
    updateDialogVisible.value = true; // 显示对话框
};

// 更新科室信息的函数
const updateClinicInfo = async () => {
    try {
        const response = await updateClinicService(updateClinic.value); // 调用更新服务
        if (response.code === 0) {
            ElMessage.success('更新成功');
            updateDialogVisible.value = false; // 关闭对话框
            fetchClinics(); // 重新获取科室列表
        } else {
            ElMessage.error(response.message || '更新失败');
        }
    } catch (error) {
        ElMessage.error('更新失败');
    }
};
</script>

<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加科室</el-button>
    <el-table :data="paginatedClinics" style="width: 100%">
      <el-table-column prop="clinicId" label="科室ID" width="100"></el-table-column>
      <el-table-column prop="clinicName" label="科室名称" width="150"></el-table-column>
      <el-table-column prop="clinicDescription" label="科室描述" width="800"></el-table-column>
      <!-- <el-table-column prop="departmentId" label="部门ID" width="100"></el-table-column> -->
      <el-table-column prop="departmentName" label="部门名称" width="100"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="openUpdateDialog(scope.row)">更新</el-button>
          <el-button size="mini" type="danger" @click="deleteClinic(scope.row.clinicId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页 -->
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="clinics.length"
      layout="total, prev, pager, next, jumper"
    ></el-pagination>

    <!-- 添加科室信息的对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加科室信息"
      width="400px"
    >
      <el-form :model="newClinic" label-width="120px">
        <el-form-item label="科室ID">
          <el-input v-model="newClinic.clinicId" placeholder="请输入科室ID" disabled></el-input>
        </el-form-item>
        <el-form-item label="科室名称">
          <el-input v-model="newClinic.clinicName" placeholder="请输入科室名称"></el-input>
        </el-form-item>
        <el-form-item label="科室描述">
          <el-input type="textarea" v-model="newClinic.clinicDescription" placeholder="请输入科室描述"></el-input>
        </el-form-item>
        <el-form-item label="部门ID">
          <el-select v-model="newClinic.departmentId" placeholder="请选择部门">
            <el-option
              v-for="department in departments"
              :key="department.id"
              :label="department.name"
              :value="department.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClinic">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 添加更新科室信息的对话框 -->
    <el-dialog
      v-model="updateDialogVisible"
      title="更新科室信息"
      width="400px"
    >
      <el-form :model="updateClinic" label-width="120px">
        <el-form-item label="科室ID">
          <el-input v-model="updateClinic.clinicId" placeholder="请输入科室ID" disabled></el-input>
        </el-form-item>
        <el-form-item label="科室名称">
          <el-input v-model="updateClinic.clinicName" placeholder="请输入科室名称"></el-input>
        </el-form-item>
        <el-form-item label="科室描述">
          <el-input type="textarea" v-model="updateClinic.clinicDescription" placeholder="请输入科室描述"></el-input>
        </el-form-item>
        <el-form-item label="部门ID">
          <el-select v-model="updateClinic.departmentId" placeholder="请选择部门">
            <el-option
              v-for="department in departments"
              :key="department.id"
              :label="department.name"
              :value="department.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateClinicInfo">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 添加样式 */
</style>